package com.guilin.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.guilin.common.core.domain.model.LoginUser;
import com.guilin.common.utils.SecurityUtils;
import com.guilin.common.utils.StringUtils;
import com.guilin.framework.web.service.TokenService;

/**
 * token过滤器 验证token有效性
 * 
 *
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {

        // 1. 从请求中获取用户信息
        LoginUser loginUser = tokenService.getLoginUser(request);

        // 2. 如果用户存在且当前未认证
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            // 3. 验证令牌有效性（如过期、篡改）
            tokenService.verifyToken(loginUser);

            // 4. 构建认证对象 principal：认证主体（用户信息）credentials：凭证（JWT 令牌，此处设为 null 表示已认证）authorities：用户权限列表
            //未认证令牌：new UsernamePasswordAuthenticationToken(username, password)
            //已认证令牌：包含完整用户信息和权限
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());

            // 5. 设置权限信息
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            // 6. 将认证信息存入当前线程上下文
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }

        // 7. 放行请求
        chain.doFilter(request, response);
    }
}
